<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { RequestPath, startRequest } from '../base/RequestWork';
import { ElMessage } from 'element-plus';
// 用户数指标
let userCountDataOptions = ref({
    allCount: 0,
    title: { text: "近一月新增用户", left: "center" },
    xAxis:{
        data: getLastMonthDates(),
        axisLabel: { interval:0 }
    },
    yAxis:{},
    series: [{
        name: "用户数", type: "bar", data: [] as any 
    }]
});

let userActiveDataOptions = ref({
    allCount: 0,
    title: { text: "近一月活跃用户", left: "center" },
    xAxis:{
        data: getLastMonthDates(),
        axisLabel: { interval:0 }
    },
    yAxis:{},
    series: [{
        name: "活跃用户", type: "bar", data: [] as any 
    }]
});

let orderCountDataOptions = ref({
    allCount: 0,
    title: { text: "近一月新增订单", left: "center" },
    xAxis:{
        data: getLastMonthDates(),
        axisLabel: { interval:0 }
    },
    yAxis:{},
    series: [{
        name: "订单数", type: "bar", data: [] as any 
    }]
});

let billDataOptions = ref({
    allCount: 0,
    title: { text: "近一月销售额（￥）", left: "center" },
    xAxis:{
        data: getLastMonthDates(),
        axisLabel: { interval:0 }
    },
    yAxis:{},
    series: [{
        name: "销售额", type: "bar", data: [] as any 
    }]
});

let evaluationCountDataOptions = ref({
    allCount: 0,
    title: { text: "近一月新增评价", left: "center" },
    xAxis:{
        data: getLastMonthDates(),
        axisLabel: { interval:0 }
    },
    yAxis:{},
    series: [{
        name: "评价数", type: "bar", data: [] as any 
    }]
});

onMounted(()=>{
    // 调用各个数据指标的数据获取方法
    getUserCountData()
    getUserActiveData()
    getOrderCountData()
    getBillData()
    getEvaluationCountData()
})

function getUserCountData() {
    startRequest(RequestPath.statisticalGet, 'get', {type: 0}).then((response)=>{
        // 修复：直接访问response.data，而不是response.data.data
        if (!response?.data) {
            console.error('获取用户统计数据失败：响应数据为空');
            ElMessage.error('获取用户统计数据失败');
            return;
        }
        
        // 对总数属性进行赋值
        userCountDataOptions.value.allCount = response.data.allCount || 0;
        // 服务端返回的最近一月的数据
        let datas = response.data.datas || [];
        // 用来绘制图表的结果列表
        let result = [];
        // 最近一个月的日期
        let dates = getLastMonthDates();
        for (let i = 0; i < dates.length; i++) {
            let date = dates[i];
            // 从服务端数据中查找此日期的数据
            let d = datas.filter((item:any)=>{
                if (getMonthDay(item.date) == date) { return true; }
                return false;
            }).pop();
            // 有数据则放入列表中，否则用0填充
            if (d) {
                result.push(d.count);
            } else {
                result.push(0);
            }
        }
        
        // 安全检查series数组
        if (userCountDataOptions.value.series && userCountDataOptions.value.series.length > 0) {
            userCountDataOptions.value.series[0].data = result;
        } else {
            console.warn('userCountDataOptions的series数组为空');
        }
    }).catch((error)=>{
        ElMessage.error({
            message: error?.response?.data?.error || '获取用户统计数据失败'
        });
    });
}

function getUserActiveData() {
    startRequest(RequestPath.statisticalGet, 'get', {type: 1}).then((response)=>{
        // 修复：直接访问response.data，而不是response.data.data
        if (!response?.data) {
            console.error('获取用户活跃数据失败：响应数据为空');
            ElMessage.error('获取用户活跃数据失败');
            return;
        }
        
        // 对属性进行赋值
        userActiveDataOptions.value.allCount = response.data.allCount || 0;
        let datas = response.data.datas || [];
        let result = [];
        let dates = getLastMonthDates();
        for (let i = 0; i < dates.length; i++) {
            let date = dates[i];
            let d = datas.filter((item:any)=>{
                if (getMonthDay(item.date) == date) { return true; }
                return false;
            }).pop();
            if (d) {
                result.push(d.count);
            } else {
                result.push(0);
            }
        }
        
        // 安全检查series数组
        if (userActiveDataOptions.value.series && userActiveDataOptions.value.series.length > 0) {
            userActiveDataOptions.value.series[0].data = result;
        } else {
            console.warn('userActiveDataOptions的series数组为空');
        }
    }).catch((error)=>{
        ElMessage.error({
            message: error?.response?.data?.error || '获取用户活跃数据失败'
        });
    });
}

function getOrderCountData() {
    startRequest(RequestPath.statisticalGet, 'get', {type: 2}).then((response)=>{
        // 修复：直接访问response.data，而不是response.data.data
        if (!response?.data) {
            console.error('获取订单数据失败：响应数据为空');
            ElMessage.error('获取订单数据失败');
            return;
        }
        
        // 对属性进行赋值
        orderCountDataOptions.value.allCount = response.data.allCount || 0;
        let datas = response.data.datas || [];
        let result = [];
        let dates = getLastMonthDates();
        for (let i = 0; i < dates.length; i++) {
            let date = dates[i];
            let d = datas.filter((item:any)=>{
                if (getMonthDay(item.date) == date) { return true; }
                return false;
            }).pop();
            if (d) {
                result.push(d.count);
            } else {
                result.push(0);
            }
        }
        
        // 安全检查series数组
        if (orderCountDataOptions.value.series && orderCountDataOptions.value.series.length > 0) {
            orderCountDataOptions.value.series[0].data = result;
        } else {
            console.warn('orderCountDataOptions的series数组为空');
        }
    }).catch((error)=>{
        ElMessage.error({
            message: error?.response?.data?.error || '获取订单数据失败'
        });
    });
}

function getBillData() {
    startRequest(RequestPath.statisticalGet, 'get', {type: 3}).then((response)=>{
        // 修复：直接访问response.data，而不是response.data.data
        if (!response?.data) {
            console.error('获取销售额数据失败：响应数据为空');
            ElMessage.error('获取销售额数据失败');
            return;
        }
        
        // 对属性进行赋值
        billDataOptions.value.allCount = response.data.allCount || 0;
        let datas = response.data.datas || [];
        let result = [];
        let dates = getLastMonthDates();
        for (let i = 0; i < dates.length; i++) {
            let date = dates[i];
            let d = datas.filter((item:any)=>{
                if (getMonthDay(item.date) == date) { return true; }
                return false;
            }).pop();
            if (d) {
                result.push(d.count);
            } else {
                result.push(0);
            }
        }
        
        // 安全检查series数组
        if (billDataOptions.value.series && billDataOptions.value.series.length > 0) {
            billDataOptions.value.series[0].data = result;
        } else {
            console.warn('billDataOptions的series数组为空');
        }
    }).catch((error)=>{
        ElMessage.error({
            message: error?.response?.data?.error || '获取销售额数据失败'
        });
    });
}

function getEvaluationCountData() {
    // 修复：将type从0改为4（评价统计）
    startRequest(RequestPath.statisticalGet, 'get', {type: 4}).then((response)=>{
        // 修复：直接访问response.data，而不是response.data.data
        if (!response?.data) {
            console.error('获取评价数据失败：响应数据为空');
            ElMessage.error('获取评价数据失败');
            return;
        }
        
        // 对属性进行赋值
        evaluationCountDataOptions.value.allCount = response.data.allCount || 0;
        let datas = response.data.datas || [];
        let result = [];
        let dates = getLastMonthDates();
        for (let i = 0; i < dates.length; i++) {
            let date = dates[i];
            let d = datas.filter((item:any)=>{
                if (getMonthDay(item.date) == date) { return true; }
                return false;
            }).pop();
            if (d) {
                result.push(d.count);
            } else {
                result.push(0);
            }
        }
        
        // 安全检查series数组
        if (evaluationCountDataOptions.value.series && evaluationCountDataOptions.value.series.length > 0) {
            evaluationCountDataOptions.value.series[0].data = result;
        } else {
            console.warn('evaluationCountDataOptions的series数组为空');
        }
    }).catch((error)=>{
        ElMessage.error({
            message: error?.response?.data?.error || '获取评价数据失败'
        });
    });
}

// 获取近1月的日期
function getLastMonthDates() {
  let dates = [];
  // 当前日期
  let currentDate = new Date();
  // 取最近30天
  for (let i = 29; i >= 0; i--) {
    let date = new Date(currentDate);
    date.setDate(currentDate.getDate() - i);
    // 解析出月、日信息
    let month = date.getMonth() + 1;
    let day = date.getDate();
    dates.push(month + '/' + day);
  } 
  return dates;
}

// 将日期进行格式化
function getMonthDay(date: string): string {
    let newDate = new Date(date);
    let month = newDate.getMonth() + 1;
    let day = newDate.getDate();
    return month + '/' + day
}

</script>

<template>
  <div class="container">
    <div class="stats-container">
      <!-- 用户数统计卡片 -->
      <div class="stat-card">
        <div class="stat-title">
          <span class="icon icon-user">U</span>
          总用户数
        </div>
        <div class="stat-count">{{ userCountDataOptions.allCount }}</div>
        <div class="chart-container">
          <v-chart :option="userCountDataOptions" style="height: 100%;" />
        </div>
      </div>

      <!-- 活跃用户统计卡片 -->
      <div class="stat-card">
        <div class="stat-title">
          <span class="icon icon-active">A</span>
          昨日活跃用户数
        </div>
        <div class="stat-count">{{ userActiveDataOptions.allCount }}</div>
        <div class="chart-container">
          <v-chart :option="userActiveDataOptions" style="height: 100%;" />
        </div>
      </div>

      <!-- 订单数统计卡片 -->
      <div class="stat-card">
        <div class="stat-title">
          <span class="icon icon-order">O</span>
          总订单数
        </div>
        <div class="stat-count">{{ orderCountDataOptions.allCount }}</div>
        <div class="chart-container">
          <v-chart :option="orderCountDataOptions" style="height: 100%;" />
        </div>
      </div>

      <!-- 销售额统计卡片 -->
      <div class="stat-card">
        <div class="stat-title">
          <span class="icon icon-sales">¥</span>
          总销售额
        </div>
        <div class="stat-count">¥{{ billDataOptions.allCount }}</div>
        <div class="chart-container">
          <v-chart :option="billDataOptions" style="height: 100%;" />
        </div>
      </div>

      <!-- 评价数统计卡片 -->
      <div class="stat-card">
        <div class="stat-title">
          <span class="icon icon-review">R</span>
          总评价数
        </div>
        <div class="stat-count">{{ evaluationCountDataOptions.allCount }}</div>
        <div class="chart-container">
          <v-chart :option="evaluationCountDataOptions" style="height: 100%;" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 主容器样式 */
.container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 统计卡片样式 */
.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.15);
}

/* 统计标题样式 */
.stat-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-count {
  font-size: 24px;
  font-weight: 700;
  color: #1890ff;
  margin-bottom: 15px;
}

/* 图表容器样式 */
.chart-container {
  height: 200px;
  margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-container {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .stat-card {
    padding: 15px;
  }
  
  .stat-count {
    font-size: 20px;
  }
}

/* 加载状态样式 */
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #666;
}

/* 图标样式 */
.icon {
  width: 20px;
  height: 20px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-size: 12px;
  font-weight: bold;
}

.icon-user { background-color: #1890ff; color: white; }
.icon-active { background-color: #52c41a; color: white; }
.icon-order { background-color: #faad14; color: white; }
.icon-sales { background-color: #f5222d; color: white; }
.icon-review { background-color: #722ed1; color: white; }
</style>